package com.kylin.module.admin.business;

import java.util.Date;
import java.util.List;

import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;

import org.apache.log4j.Logger;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Expression;
import org.hibernate.criterion.LogicalExpression;

import com.kylin.common.Constants;
import com.kylin.common.dict.orm.Dict;
import com.kylin.common.exception.BusinessException;
import com.kylin.common.exception.SystemException;
import com.kylin.common.paginate.DisplayPage;
import com.kylin.common.paginate.PageManager;
import com.kylin.common.util.FileOperater;
import com.kylin.common.util.MemObjFactory;
import com.kylin.common.util.UTool;
import com.kylin.common.util.UUID;
import com.kylin.hibernate.BaseHibernateDAO;
import com.kylin.hibernate.CriteriaInfo;
import com.kylin.hibernate.PropertyCondition;
import com.kylin.module.shop.orm.Company;
import com.kylin.module.shop.orm.Product;
import com.kylin.module.user.orm.User;

public class ManageShopBlogic {
	protected static Logger log = Logger.getLogger(ManageShopBlogic.class);
	int pageSize = 15;
 	
	/**
	 * 获取公司类型的用户列表
	 * @param pageNum
	 * @param cinfo
	 * @return
	 * @throws BusinessException
	 */
	public DisplayPage getCompanyUserList(int pageNum, CriteriaInfo cinfo) throws BusinessException {
 		log.info("search RegCompany page " + pageNum);
 		DisplayPage page = PageManager.getDisplayPage(pageSize, pageNum, cinfo);
		for(int i= 0;i < page.getList().size(); i ++){
			User user = (User)page.getList().get(i);
			user.setSubs( getUserCompanys(user.getId()) );
		}
// 		if(page.getList() != null && page.getList().size() > 0){
// 			LogicalExpression expr = null;
// 			
// 			/** 
// 			 * 实现一条sql：select company from tab 
// 			 *              where   company.user=user1 and company.language=language1
// 			 *                   or company.user=user2 and company.language=language2
// 			 *                   or .......
// 			 *  */
// 			for(int i= 0;i < page.getList().size(); i ++){
// 				User user = (User)page.getList().get(i);
// 				user.getLanguage();
// 				
// 				Criterion critA = BaseHibernateDAO.getCriterion("user", user,PropertyCondition.OPERATOR_EQ);
// 				Criterion critB = BaseHibernateDAO.getCriterion("language", user.getLanguage(),PropertyCondition.OPERATOR_EQ);
// 				LogicalExpression and = Expression.and(critA,critB);
// 				if(expr == null)
// 					expr = and;
// 				else
// 					expr = Expression.or(expr, and);
// 			}
// 			System.out.println("EXPR::"+expr);
// 			Criteria criteria = BaseHibernateDAO.createCriteria(expr,Company.class);
// 			page.setList(criteria.list());
// 		}
 		page.setSearchId(""+cinfo.hashCode());
			System.out.println("\nSIZE::"+page.getList().size());
 		return page;
 	}

 	/**
 	 * 获取指定用户拥有的所有语言版本的公司集合
 	 * @param userid
 	 * @return
 	 * @throws BusinessException
 	 */
 	public List getUserCompanys(Long userid)throws BusinessException {
 		log.info("getRegCompany detail " );
 		User user = (User) BaseHibernateDAO.findById(User.class, userid);
		PropertyCondition[] pConditions = new PropertyCondition[] {
				new PropertyCondition("user", user,PropertyCondition.OPERATOR_EQ ),
		};				
		return BaseHibernateDAO.findByPropertyConditions(Company.class, pConditions, null);
 	}
 	
 	/**
 	 * 激活用户
 	 * @param id
 	 * @return 返回激活邮件的内容
 	 * @throws BusinessException
 	 */
 	public String activationRegCompany(Long id) throws BusinessException{
 		User user = (User) BaseHibernateDAO.findById(User.class, id);
 		try {
			InternetAddress.parse(user.getEmail());
		} catch (AddressException e) {
			throw new BusinessException("此用户邮件地址无效，不能激活",e);
		}
 		user.setActive(Constants.ACTIVE_ON);
 		String password = UUID.create().substring(0,7);
 		user.setPassword(password);
 		user.setLastupdatedon(new Date());
 		BaseHibernateDAO.update(user);		
 		List coms = BaseHibernateDAO.findByProperty(Company.class, "user", user);
 		if(coms != null && coms.size()>0){
 			for(int i=0;i<coms.size();i++){
 			    Company com = (Company)coms.get(i);
 			    com.setActive(Constants.ACTIVE_ON);
 			   BaseHibernateDAO.update(com);
 			}
 		}
 		try{
 		String content = UTool.sendActivationMail(user.getUsername(),user.getPassword(),user.getEmail(),user.getLanguage());
 		return content;
 		}catch(Exception e){
 			user.setActive(Constants.ACTIVE_WAIT);
 	 		user.setLastupdatedon(new Date());
//user.set
 	 		BaseHibernateDAO.update(user);	
 			log.error("发送激活邮件失败 "+e,e);
 			throw new BusinessException("发送激活邮件失败 "+e,e);
 		}
 	}
 	
 	/**
 	 * 设置公司帐户状态
 	 * 当前是按照用户名设定状态，所有语言版本的公司帐户统一设定
 	 * @param id
 	 * @throws BusinessException
 	 */
 	public void setCompanyActive(Long id,Short active) throws BusinessException{
 		log.info("设置公司帐户状态" + id);
		User user = (User) BaseHibernateDAO.findById(User.class, id);
 		user.setActive(active);
 		BaseHibernateDAO.update(user);
 		List list = BaseHibernateDAO.findByProperty(Company.class, "user", user);
 		// 设置所有语言版本
 		for(int i=0;i<list.size();i++){
 			Company sub = (Company) list.get(i);
 			sub.setActive(active);
 			BaseHibernateDAO.update(sub);
 		}
 	}
 	
 	public static void main(String[] s){
 		LogicalExpression all = null;
			Criterion conA = BaseHibernateDAO.getCriterion("user", "lzh",PropertyCondition.OPERATOR_EQ);
				Criterion conB = BaseHibernateDAO.getCriterion("language", "zh_CN",PropertyCondition.OPERATOR_EQ);
				all = Expression.and(conA,conB);
				//all = Expression.or(all,subcriteria);
				Criterion conC = BaseHibernateDAO.getCriterion("c", "vc",PropertyCondition.OPERATOR_EQ);
				Criterion conD = BaseHibernateDAO.getCriterion("d", "vd",PropertyCondition.OPERATOR_EQ);
				LogicalExpression and2 = Expression.and(conC,conD);
				all = Expression.or(all,and2);
				Criterion cone = BaseHibernateDAO.getCriterion("e", "ve",PropertyCondition.OPERATOR_EQ);
				Criterion conf = BaseHibernateDAO.getCriterion("f", "vf",PropertyCondition.OPERATOR_EQ);
				LogicalExpression and3 = Expression.and(cone,conf);
				all =Expression.or(all,and3);
		System.out.println("all ="+all.toString());
 	}
 	
 	/**
 	 * 修改产品类别的所属父类，即移动更换产品类别的目录
 	 * @param ids
 	 * @param parentId
 	 * @throws BusinessException 
 	 * @throws NumberFormatException 
 	 */
 	public void changeProductCatsParent(String[] ids,String parentId,String language) throws NumberFormatException, BusinessException{
 		if(ids == null || parentId == null)
 			throw new SystemException("参数错误，不能修改产品类别的所属目录");
		Dict parent = (Dict)BaseHibernateDAO.findById(Dict.class, new Long(parentId));
 		for(int i=0;i<ids.length;i++){
 			Dict sub = (Dict)BaseHibernateDAO.findById(Dict.class, new Long(ids[i]));
 			sub.setParent(parent);
 			BaseHibernateDAO.update(sub);
 		}
 		MemObjFactory.reloadDict(parent.getCatdict());
 	}
}
